# -*- coding: utf-8 -*-
"""
版权所有：J哥
微信号：wws_0904
author : Laity
Description: 工具类 ：实现重写 JWT的相应数据
JWT默认的响应数据只有  token
"""
from django.contrib.auth.backends import ModelBackend
import re
from .models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """表示的是：重写JWT登录视图的构造响应数据函数，多加 user_id 和 user_username"""
    return {
        'token': token,
        'user': user.id,
        'username': user.username,
    }


def get_user_by_account(accounts):
    """
    通过传入的账号动态 获取user对象
    :param accounts: 可能是用户名 或  邮箱
    :return:  user或者None
    """
    try:
        if re.match(r'\w{1,}@\w{1,}.(com|cn|com.cn)$', accounts):
            user = User.objects.get(email=accounts)
        else:
            user = User.objects.get(username=accounts)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameEmailAuthBackend(ModelBackend):
    """
    修改django的认证类，为了实现多账户登录
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        # 获取user
        user = get_user_by_account(username)
        # 判断密码
        if user and user.check_password(password):

            return user
